package com.example.meitao.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.meitao.R;
import com.example.meitao.adapter.MyPagerAdapter;
import com.example.meitao.adapter.ShowPagerAdapter;
import com.example.meitao.bean.CommunityBean;
import com.example.meitao.bean.Discount;
import com.example.meitao.config.NetConfig;
import com.example.meitao.netinterface.NetInterface;
import com.example.meitao.ui.MainActivity;
import com.example.meitao.task.DiscountNetTask;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Retrofit;

/**
 * Created by 星星 on 2016/8/30.
 */
public class CommunityFragment extends Fragment{
    private LinearLayout mLayout;
    private TabLayout mTabLayout;
    private ViewPager mViewPagerFirst;
    private ViewPager mViewPagerSecond;
    private List<Fragment> mFragment;
    private List<String> mTitles;
    private ShowPagerAdapter showPagerAdapter;
    private List<ImageView> mImageViews;
    private MyPagerAdapter mPagerAdapter;
    private List<CommunityBean.DataBean.ResultsBean> mData;

    private PagerAdapter madapter;
    private CollapsingToolbarLayout mcollapsingToolbarlayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_community, null);


        initView(view);
        initData();
        setData();
        return view;
    }

    private void setData() {


        mViewPagerFirst.setAdapter(mPagerAdapter);
        mViewPagerSecond.setAdapter(showPagerAdapter);
        //设置viewPager和TabLayout联动
        mTabLayout.setupWithViewPager(mViewPagerSecond);
        //设置预加载的页数
        mViewPagerSecond.setOffscreenPageLimit(3);
        mTabLayout.setTabMode(TabLayout.MODE_FIXED);
    }

    private void initData() {
        mPagerAdapter = new MyPagerAdapter(mImageViews);
        RequestParams params = new RequestParams(NetConfig.COMMUNITY_PATH);
        final ImageOptions imageOptions = new ImageOptions.Builder()
                .setSize(DensityUtil.dip2px(80), DensityUtil.dip2px(80))//图片大小
                .setRadius(DensityUtil.dip2px(3))//ImageView圆角半径
                .setCrop(true)// 如果ImageView的大小不是定义为wrap_content, 不要crop.
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLoadingDrawableId(R.mipmap.ic_launcher)//加载中默认显示图片
                .setFailureDrawableId(R.mipmap.ic_launcher)//加载失败后默认显示图片
                .build();
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                CommunityBean communityBean = gson.fromJson(result, CommunityBean.class);
                List<CommunityBean.DataBean.TagsBean> tagsList = communityBean.getData().getTags();
                for (int i = 0; i < tagsList.size(); i++) {
                    View scrollItem = View.inflate(getActivity(),R.layout.item_community_head_scroll,null);
                    //设置给scrollView的LinearLayout
                    TextView textViewTitle = (TextView) scrollItem.findViewById(R.id.tv_head_item_title);
                    textViewTitle.setText(tagsList.get(i).getTagname());
                    ImageView imageViewShow = (ImageView) scrollItem.findViewById(R.id.iv_head_item_show);
                    x.image().bind(imageViewShow,tagsList.get(i).getPic_filename(),imageOptions);
                    mLayout.addView(scrollItem);
                }
                List<CommunityBean.DataBean.TopcontentsBean> topcontents = communityBean.getData().getTopcontents();
                for (int i = 0; i < topcontents.size(); i++) {
                    ViewPager.LayoutParams params = new ViewPager.LayoutParams();
                    //设置imageView填充整个父控件，就相当于在xml里面写了match_parent
                    params.height = ViewGroup.LayoutParams.MATCH_PARENT;
                    params.width = ViewGroup.LayoutParams.MATCH_PARENT;

                    ImageView imageView = new ImageView(getActivity());
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);

                    imageView.setLayoutParams(params);
                    String s = topcontents.get(i).getPic();
                    Picasso.with(getActivity()).load(s).into(imageView);
                    mImageViews.add(imageView);


                    mPagerAdapter.notifyDataSetChanged();
                    //设置Page间间距
                    mViewPagerFirst.setPageMargin(20);
                    //设置缓存的页面数量
                    mViewPagerFirst.setOffscreenPageLimit(3);
                    mViewPagerFirst.setAdapter(madapter = new PagerAdapter()
                    {
                        @Override
                        public Object instantiateItem(ViewGroup container, final int position)
                        {
                            final ImageView view = new ImageView(getActivity());
                            new DiscountNetTask(){
                                @Override
                                public void onCallBack(Discount result) {
                                  //***不能最后一张**
                                    Picasso.with(getActivity()).load(result.getData()
                                            .getToplist().get(position).getPic()).into(view);
                                }
                            }.execute(NetConfig.DISCOUNT_PATH);
                            container.addView(view);
                            return view;
                        }

                        @Override
                        public void destroyItem(ViewGroup container, int position, Object object)
                        {
                            container.removeView((View) object);
                        }

                        @Override
                        public int getCount()
                        {
                            return mImageViews.size();
                        }

                        @Override
                        public boolean isViewFromObject(View view, Object o)
                        {
                            return view == o;
                        }
                    });


                }


                mData = communityBean.getData().getResults();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getActivity(), "网络连接异常，请检查网络连接！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });


        for (int i = 0; i < 4; i++) {
            //  mFragment.add(new MyFragment());
            switch (i) {
                case 0 :
                    mTitles.add("心得");
                    mFragment.add(new StudyFragment());

                    break;
                case 1 :
                    mTitles.add("拼单");
                    mFragment.add(new TogetherFragment());
                    break;
                case 2 :
                    mTitles.add("爆料");
                    mFragment.add(new SayFragment());

                    break;
                case 3 :
                    mTitles.add("我关注的");
                    mFragment.add(new FollowFragment());
                    break;
            }
        }
        showPagerAdapter = new ShowPagerAdapter(getChildFragmentManager(),mFragment,mTitles);
    }

    private void initView(View view) {
        mTitles=new ArrayList<>();
        mFragment=new ArrayList<>();
        mImageViews = new ArrayList<>();
        mData = new ArrayList<>();
        mViewPagerFirst = (ViewPager) view.findViewById(R.id.vp_community_first);
        mViewPagerSecond = (ViewPager) view.findViewById(R.id.vp_community_second);
        mLayout = (LinearLayout) view.findViewById(R.id.ll_community_scroll);
        mTabLayout = (TabLayout) view.findViewById(R.id.tablayout_community_test);



        mcollapsingToolbarlayout = (CollapsingToolbarLayout) view.findViewById(R.id.cl_collapsing_test);
        //设置toolbar的字体颜色(拉下来的颜色)
        mcollapsingToolbarlayout.setExpandedTitleColor(Color.WHITE);
        //toolbar滑上去的颜色
        mcollapsingToolbarlayout.setCollapsedTitleTextColor(Color.BLACK);
        //Toolbar折叠之后的颜色
        mcollapsingToolbarlayout.setContentScrimColor(Color.YELLOW);

    }
}
